﻿using Abp.Web.Models;
using MyCompanyName.AbpZeroTemplate.Agent;
using MyCompanyName.AbpZeroTemplate.Agent.Dto;
using MyCompanyName.AbpZeroTemplate.Authorization.Users;
using MyCompanyName.AbpZeroTemplate.Web.Areas.Mpa.Models.Agent;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace MyCompanyName.AbpZeroTemplate.Web.Areas.Mpa.Controllers
{
    public class AgentController : Controller
    {

        private readonly IAgentService _agentAppService;
        private readonly IUserAppService _userAppService;
        public AgentController(IAgentService agentAppService, IUserAppService userAppService)
        {
            _agentAppService = agentAppService;
            _userAppService = userAppService;
        }
        // GET: Mpa/Agent
        public ActionResult Index()
        {
            return View();
        }
        #region 代理商
        public ActionResult AgentList()
        {

            return View();
        }
        /// <summary>
        /// 异步获得客户的DataTable数据
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        /// 
        [DontWrapResult]
        public ActionResult GetAgentDataTable(int offset, int limit, string Filter1SearchName)
        {
            string AgentName = "";
            //参数
            string Filter1SearchNamea = Request["Filter1SearchName"];
            AgentName = Filter1SearchName;
            int PageSize = limit;
            int PageNumber = (offset / limit) + 1;
            //获得数据
            var result = _agentAppService.GetAgentDtoList(AgentName, PageSize, PageNumber);
            //var resultGet = result.Skip(offset).Take(limit).ToList();
            object data = new { total = result.Items.Count, rows = result.Items };
            return Json(data, JsonRequestBehavior.AllowGet);


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="AgentId"></param>
        /// <returns></returns>
        public ActionResult CreteOrUpdate(int AgentId)
        {
            AgentDto agent = new AgentDto();
            if (AgentId != 0)
            {
                agent = _agentAppService.GetAgentById(AgentId);
            }
            return View(agent);
        }

        /// <summary>
        /// 提交代理商创建的表单
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<JsonResult> AgentCreateForm(CreateAgentInput input)
        {
            bool IsSuccess = true;
            string ErrorMsg = "";

            try
            {
                //创建代理商用户,默认密码：身份证前5位 +.com
                await _userAppService.CreateOrUpdateUser(new Authorization.Users.Dto.CreateOrUpdateUserInput()
                {
                    User = new Authorization.Users.Dto.UserEditDto()
                    {
                        Name = input.AgentName,
                        EmailAddress = input.AgentCode + "@126.com",
                        IsActive = true,
                        PhoneNumber = input.TelePhone,
                        UserName = input.AgentCode,
                        ShouldChangePasswordOnNextLogin = true,
                        Surname = input.AgentName,
                        IsLockoutEnabled = input.IsDisabled == 1 ? true : false,
                        Password = input.IdCard.Substring(0, 5) + ".com"
                    },
                    AssignedRoleNames = new string[] { "User" },
                    SendActivationEmail = false,
                    SetRandomPassword = false
                });
                //Create
                //获得新增的用户的Id根据用户名
                User user = _agentAppService.GetUserIdByAgentCode(input.AgentCode);
                if (user != null)
                {
                    //获取当前代理商的信息
                    AgentDto agent = _agentAppService.GetAgentByAgentCode(User.Identity.Name);

                    input.OwnerId = user.Id.ToString();
                    input.Proportion = agent.Proportion;
                    //input.ParentAgent = User.Identity.Name;
                    if (agent != null)
                    {
                        if (agent.AgentLevel == 0)
                        {
                            //input.FirstAgentCode = agent.AgentCode;
                            input.AgentLevel = 1;
                            _agentAppService.CreateAgent(input);
                            ErrorMsg = "创建成功";
                        }
                        else if (agent.AgentLevel == 1)
                        {
                            input.FirstAgentCode = agent.AgentCode;
                            input.AgentLevel = 2;
                            _agentAppService.CreateAgent(input);
                            ErrorMsg = "创建成功";
                        }
                        else if (agent.AgentLevel == 2)
                        {
                            input.SecondAgentCode = agent.AgentCode;
                            input.AgentLevel = 3;
                            _agentAppService.CreateAgent(input);
                            ErrorMsg = "创建成功";
                        }
                        else
                        {
                            IsSuccess = false;
                            ErrorMsg = "创建失败，该代理商不能创建下级代理商";
                        }
                    }
                    else
                    {
                        IsSuccess = false;
                        ErrorMsg = "创建失败，没有当前代理商信息";
                    }
                }
                else
                {
                    IsSuccess = false;
                    ErrorMsg = "创建失败,没有找到用户信息";
                }
            }
            catch (Exception ex)
            {
                IsSuccess = false;
                ErrorMsg = "创建失败" + ex.Message;
            }
            return Json(
                new
                {
                    status = IsSuccess,
                    errormsg = ErrorMsg
                });

        }
        /// <summary>
        /// 提交代理商创建的表单
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult AgentUpdateForm(UpdateAgentInput model)
        {
            bool IsSuccess = true;
            string ErrorMsg = "";

            try
            {
                var result = _agentAppService.UpdateAgent(model);
                if (result == true)
                {
                    IsSuccess = true;
                    ErrorMsg = "修改成功";
                }
                else
                {
                    IsSuccess = false;
                    ErrorMsg = "修改失败";
                }
            }
            catch (Exception ex)
            {
                IsSuccess = false;
                ErrorMsg = "修改失败" + ex.Message;
            }
            return Json(
                new
                {
                    status = IsSuccess,
                    errormsg = ErrorMsg
                });
        }
        #endregion

        #region 代理商转账
        /// <summary>
        /// 代理商转账列表
        /// </summary>
        /// <returns></returns>
        public ActionResult AgentTransferList()
        {
            return View();
        }

        /// <summary>
        /// 异步获得代理商转账记录的DataTable数据
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [DontWrapResult]
        public ActionResult GetAgentTransferDataTable(int offset, int limit, string Filter1SearchName)
        {
            string AgentTransferName = "";
            //参数
            string Filter1SearchNamea = Request["Filter1SearchName"];
            AgentTransferName = Filter1SearchName;
            int PageSize = limit;
            int PageNumber = (offset / limit) + 1;
            //获得数据
            var result = _agentAppService.GetAgentTransferDtoList(AgentTransferName, PageSize, PageNumber);
            //var resultGet = result.Skip(offset).Take(limit).ToList();
            object data = new { total = result.Items.Count, rows = result.Items };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 代理商转账信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AgentTransfer()
        {
            return View();
        }

        /// <summary>
        /// 根据代理商账号获得代理商的名称、流量、身份证号、联系电话、地址等信息
        /// </summary>
        /// <param name="AccountCode"></param>
        /// <returns></returns>
        [DontWrapResult]
        public ActionResult GetMsgByAgentCode(string AgentCode)
        {
            //根据代理商账号获得获得代理商的
            AgentDto agent = new AgentDto();
            if (!string.IsNullOrEmpty(AgentCode))
            {
                agent = _agentAppService.GetAgentByAgentCode(AgentCode);
            }
            AgentTransferViewModel agentTransferViewModel = new AgentTransferViewModel();

            //只能对下线代码商转账
            string ParentAgent = "";
            if (agent != null && agent.AgentLevel == 3)
            {
                AgentDto agent1 = _agentAppService.GetAgentByAgentCode(agent.SecondAgentCode);
                ParentAgent = agent1.AgentName;
            }
            else if (agent != null && agent.AgentLevel == 2)
            {
                AgentDto agent2 = _agentAppService.GetAgentByAgentCode(agent.FirstAgentCode);
                ParentAgent = agent2.AgentName;
            }

            if (agent != null && ((ParentAgent != "" && ParentAgent == User.Identity.Name) || User.Identity.Name.Equals(("admin"))))
            {
                agentTransferViewModel.AgentCode = agent.AgentCode;
                agentTransferViewModel.AgentName = agent.AgentName;
                agentTransferViewModel.Balance = agent.Balance;
                agentTransferViewModel.RechargeBalance = agent.BalanceRecharge;
                agentTransferViewModel.IdCard = agent.IdCard;
                agentTransferViewModel.Telephone = agent.TelePhone;
                agentTransferViewModel.Adress = agent.Address;
            }
            return Json(agentTransferViewModel);
        }

        /// <summary>
        /// 代理商转账信息处理
        /// </summary>
        /// <returns></returns>
        public ActionResult AgentTransfers(CreateAgentTransferInput input)
        {

            //检查充值代理商的有效性
            //根据代理商账号获得获得代理商的
            AgentDto agent = new AgentDto();
            if (!string.IsNullOrEmpty(input.ReceiveRechargeAgentCode))
            {
                agent = _agentAppService.GetAgentByAgentCode(input.ReceiveRechargeAgentCode);
            }

            bool isValid = false; string errormsg = ""; bool IsSuccess = true;
            //只能对下线代码商转账
            string ParentAgent = "";
            if (agent != null && agent.AgentLevel == 3)
            {
                AgentDto agent1 = _agentAppService.GetAgentByAgentCode(agent.SecondAgentCode);
                ParentAgent = agent1.AgentName;
            }
            else if (agent != null && agent.AgentLevel == 2)
            {
                AgentDto agent2 = _agentAppService.GetAgentByAgentCode(agent.FirstAgentCode);
                ParentAgent = agent2.AgentName;
            }


            if (agent != null && ParentAgent == User.Identity.Name)
            {
                isValid = true;
            }
            //else if (User.Identity.Name.Equals(("admin")))
            //{
            //    isValid = true;
            //}
            else
            {
                errormsg = "代理商账号不存在!";
                IsSuccess = false;
            }

            //1、根据转账的流量跟新两个经销商的数据
            //2、创建转账记录
            if (isValid)
            {
                string result = _agentAppService.CreateAgentTransfer(input);
                JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                string status = jo["status"].ToString();
                if (status == "False")
                {
                    IsSuccess = false;
                }
                errormsg = jo["errormsg"].ToString();
            }
            return Json(
                new
                {
                    status = IsSuccess,
                    errormsg = errormsg
                });
        }
        #endregion

        #region 代理商充值
        /// <summary>
        /// 代理商充值列表
        /// </summary>
        /// <returns></returns>
        public ActionResult AgentRechargeList()
        {
            return View();
        }
        /// <summary>
        /// 异步获得代理商充值记录的DataTable数据
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        [DontWrapResult]
        public ActionResult GetAgentRechargeDataTable(int offset, int limit, string Filter1SearchName)
        {
            string AgentRechargeName = "";
            //参数
            string Filter1SearchNamea = Request["Filter1SearchName"];
            AgentRechargeName = Filter1SearchName;
            int PageSize = limit;
            int PageNumber = (offset / limit) + 1;
            //获得数据
            var result = _agentAppService.GetAgentRechargeDtoList(AgentRechargeName, PageSize, PageNumber);
            //var resultGet = result.Skip(offset).Take(limit).ToList();
            object data = new { total = result.Items.Count, rows = result.Items };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 代理商充值
        /// </summary>
        /// <returns></returns>
        public ActionResult AgentRecharge()
        {
            return View();
        }

        /// <summary>
        /// 代理商充值
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult AgentRecharges(CreateAgentRechargeInput input)
        {
            //检查充值代理商的有效性
            //根据代理商账号获得获得代理商的
            AgentDto agent = new AgentDto();
            if (!string.IsNullOrEmpty(input.AgentCode))
            {
                agent = _agentAppService.GetAgentByAgentCode(input.AgentCode);
            }

            bool isValid = false; string errormsg = ""; bool IsSuccess = true;
            //只能对下线代码商转账
            string ParentAgent = "";
            if (agent != null && agent.AgentLevel == 3)
            {
                AgentDto agent1 = _agentAppService.GetAgentByAgentCode(agent.SecondAgentCode);
                ParentAgent = agent1.AgentName;
            }
            else if (agent != null && agent.AgentLevel == 2)
            {
                AgentDto agent2 = _agentAppService.GetAgentByAgentCode(agent.FirstAgentCode);
                ParentAgent = agent2.AgentName;
            }


            if (agent != null && ParentAgent == User.Identity.Name)
            {
                isValid = true;
            }
            //else if (User.Identity.Name.Equals(("admin")))
            //{
            //    isValid = true;
            //}
            else
            {
                errormsg = "代理商账号不存在!";
                IsSuccess = false;
            }

            //1、根据转账的流量跟新两个经销商的数据
            //2、创建转账记录
            if (isValid)
            {
                string result = _agentAppService.CreateAgentRecharge(input);
                JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                string status = jo["status"].ToString();
                if (status == "False")
                {
                    IsSuccess = false;
                }
                errormsg = jo["errormsg"].ToString();
            }
            return Json(
                new
                {
                    status = IsSuccess,
                    errormsg = errormsg
                });
        }

        #endregion
    }
}